//
//  TodayInHistoryViewController.m
//  LifeTools
//
//  Created by alex on 18/10/2016.
//  Copyright © 2016 chinaclick. All rights reserved.
//

#import "TodayInHistoryViewController.h"
#import "TodayInHistroyDataModel.h"
#import "TodayInHistoryTableViewCell.h"

@interface TodayInHistoryViewController ()<UITableViewDelegate, UITableViewDataSource> {
    NSMutableArray *dataArray;
}

@property (nonatomic) JHUD *hudView;
@property (nonatomic, strong) UITableView *tableView;

@end

@implementation TodayInHistoryViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES]; // 隐藏导航栏
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.autoresizingMask =UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;

    self.navigationItem.title = @"历史上的今天";
    [self.navigationController.navigationBar setTranslucent:NO];
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view.
    
    _tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    _tableView.delegate = self;
    _tableView.dataSource =self;
    [self.view addSubview:self.tableView];
    
    self.hudView = [[JHUD alloc]initWithFrame:self.view.bounds];
    
    __weak typeof(self)  _self = self;
    [_self loadingCircleAnimation];

    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(initData)];
    [self initData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)initData {
    dataArray = [NSMutableArray array];
    [dataArray removeAllObjects];
    
    NSDate *today = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:today];
    NSString *month = [NSString stringWithFormat:@"%ld",(long)[dateComponent month]];
    NSString *day= [NSString stringWithFormat:@"%ld",(long)[dateComponent day]];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [WTRequestCenter postWithURL:@"http://api.juheapi.com/japi/toh" parameters:@{@"key":@"e7e2f2ebe1e38b09705ee4463a5aa118", @"month": month, @"day": day} finished:^(NSURLResponse *response, NSData *data) {
            id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            if (0 == [[obj objectForKey:@"error_code"] intValue]) {
                NSMutableArray *array = [NSMutableArray array];
                array = [obj objectForKey:@"result"];
                                
                for (int i = 0; i < array.count; i++) {
                    TodayInHistroyDataModel *model = [[TodayInHistroyDataModel alloc] init];
                    model.picUrl = [array[i] objectForKey:@"pic"];
                    model.title = [array[i] objectForKey:@"title"];
                    model.des = [array[i] objectForKey:@"des"];
                    [dataArray addObject:model];
                }
                [self.tableView.mj_header endRefreshing];
                [self.hudView hide];
                [self.tableView reloadData];
            }
        } failed:^(NSURLResponse *response, NSError *error) {
             
        }];
    });
}

#pragma mark Delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    TodayInHistroyDataModel *model = dataArray[indexPath.row];
    CGSize title = [model.title boundingRectWithSize:CGSizeMake(ScreenWidth * 0.74, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]} context:nil].size;
    
    int tScale = 0;
    tScale = title.height / 16;
    
    CGSize des = [model.des boundingRectWithSize:CGSizeMake(ScreenWidth * 0.74, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]} context:nil].size;
    
    int scale = 0;
    scale = des.height / 16;
    
    NSString *platfrom = [[[[UIDevice currentDevice] machine] substringToIndex:9] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if ([platfrom isEqualToString:@"iPhone 4"] || [platfrom isEqualToString:@"iPhone 4S"]) {
        return ScreenWidth * 0.08 + ScreenWidth * (scale + 1) * 0.05 + ScreenWidth * (tScale + 1) * 0.05;
    } else {
        return ScreenWidth * 0.08 + ScreenWidth * scale * 0.05 + ScreenWidth * tScale * 0.05;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TodayInHistoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TodayInHistoryCellID"];
    cell = [[TodayInHistoryTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TodayInHistoryCellID" model:dataArray[indexPath.row]];
    
    [cell reloadData:dataArray[indexPath.row]];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(void)loadingCircleAnimation
{
    self.hudView.messageLabel.text = @"数据加载中...";
    self.hudView.indicatorBackGroundColor = [[UIColor darkGrayColor] colorWithAlphaComponent:0.1];
    self.hudView.indicatorForegroundColor = [UIColor lightGrayColor];
    [self.hudView showAtView:self.view hudType:JHUDLoadingTypeCircle];
}

@end
